package wblog.service;

import com.google.inject.Provider;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.h2.jdbcx.JdbcConnectionPool;

import javax.servlet.ServletContext;
import java.io.InputStreamReader;

public class QueryRunnerProvider implements Provider<QueryRunner> {

    private QueryRunner qr;

    public QueryRunnerProvider(ServletContext servletContext) throws Exception {
        Class.forName("org.h2.Driver");

        JdbcConnectionPool pool = JdbcConnectionPool.create("jdbc:h2:" + servletContext.getRealPath("/WEB-INF/h2") + ";LOCK_MODE=0", "sa", "");

        qr = new QueryRunner(pool);

        Object obj = qr.query("show tables", new ScalarHandler<Object>());
        if (obj == null) {
            //create tables
            StringBuilder sb = new StringBuilder();
            InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("init.sql"));
            char[] buf = new char[1024];
            int rd;
            while ((rd = reader.read(buf)) != -1) {
                sb.append(buf, 0, rd);
            }
            reader.close();
            for (String s : sb.toString().split(";")) {
                if ((s = s.trim()).isEmpty()) continue;
                qr.update(s);
            }
        }
    }

    @Override
    public QueryRunner get() {
        return qr;
    }

    public void dispose() {
        JdbcConnectionPool pool = (JdbcConnectionPool) qr.getDataSource();
        pool.dispose();
    }
}
